<?php
class OrderExt {
    public static function finishCourse($order,$fee, $transactionId){
        $order->buyerPay = $fee;
        $order->status = STATUS_BUYER_PAID;
	    $order->transaction_id = $transactionId;

        $courseUrl = "pages/classdetail/index?courseId=".$order->courseId;
        $courseObj = new Course();
        $courseObj->find($order->courseId);

        if($fee < 0){
            return false;
        }

        $user = new User();
        $user->find($order->buyerUid);

        if($order->promotionId){
            $promotion = new Promotion();
            $promotion->find($order->promotionId);
            $promotion->status = PROMOTION_USED;
            $promotion->save();
        }

        //积分和金币兑换总金额
        $notPayPrice = $order->goodsCount * $order->unitPrice - $order->promotion - $order->buyerPay;
        // if($order->buyerPay==0.01){//0yuan 订单
        //     $notPayPrice = $notPayPrice+0.01;//
        // }

        
        if($notPayPrice > 0){
            //优先用金币
            if($order->gold){
                $leftGold = $user->gold - $order->gold ;//小与1元不能用金币
                if($leftGold<0) $leftGold = 0;//扣到0
                $usedGoldCount = $user->gold - $leftGold;//本次使用shuliang
                $user->gold = $leftGold;//剩余

                //记录日志
                $log = new GoldLog();
                $log->uid = $user->uid;
                $log->gold = -$usedGoldCount;//消耗金币记为负数
                $log->info = $courseObj->courseName;
                $log->img = $courseObj->uploadImg;
                $log->url = $courseUrl;
                $log->ip  = $order->ip;
                $log->schoolId = $courseObj->schoolId;
                $log->reason = "购买课程";
                $log->save();

                $notPayPrice -=  $usedGoldCount;
                $order->gold = $usedGoldCount;
            }


            //可能用了积分
            if($order->score){
                $leftScore = $user->score - $notPayPrice * 100;
                if($leftScore<0) $leftScore = 0;//扣到0
                $usedScoreCount = abs($user->score - $leftScore);//本次使用
                $user->score = $leftScore;//剩余

                //记录日志
                $log = new ScoreLog();
                $log->uid = $user->uid;
                $log->score = -$usedScoreCount;//积分消耗记为负数
                $log->scoreType = 8;
                $log->reason = "消费抵扣";
                $log->info = $courseObj->courseName;
                $log->img = $courseObj->uploadImg;
                $log->url = $courseUrl;
                $log->ip  = $order->ip;

                $log->save();

                $notPayPrice -= $usedScoreCount/100;
                $order->score = $usedScoreCount;
            }

            

            if($notPayPrice > 0.01){//人工处理
               $order->title = $order->title ."-有".$notPayPrice."元未支付";
            }

            $saved = $user->save();
            if(!$saved){//错误
                Log::DEBUG("====error: orderId=".$order->orderId.' \$notPayPrice=$notPayPrice buyerUid='.$order->buyerUid );
                // $user->uid= $order->buyerUid;
                // $user->gold = 0;
                // $user->score = 0;
                // $user->save();//将用户虚拟资产设置为0
            }
        }


        //增加积分
        $score = intval($order->buyerPay);
        //$urlDesc,$url,$img
        if($score){
                    
            $buyerUId = $order->buyerUid;
            $reason   = "购买消费";
            $img = $courseObj->uploadImg;
                    //add($uid,$score,$scoreType,   $reason,$urlDesc,$url,$img);
            ScoreExt::add($buyerUId,$score,1,$reason,$courseObj->courseName,$courseUrl,$img);
        } 

        if($order->courseId){
            self::saveCourseLearned($order,$user);
        }
        

        $order->payTime = date('Y-m-d H:i:s');
        $saved = $order->save();

        if($saved && $order->orderType != ORDER_TYPE_LIKE){
            NoteExt::readOneOrder($order->buyerUid);
        }

        //众筹订单的处理
        if($order->orderType == ORDER_TYPE_CROWD) {
        	$base = new Base();
        	$row = $base->getOne('select * from tbl_course_crowdfunding where id = '.$order->active_id);
        	$number = $row['number_real'] + 1;
        	$sql = 'update tbl_course_crowdfunding set number_real = '.$number;
        	if($number == $row['number_total']) {
        		$sql .= ', status = 2 ';
	        }
	        $sql.=' where id = '.$order->active_id;
        	$res = $base->query($sql);
        }
        return true;
    }

    //续费订单
    public static function finishFee($order,$fee, $transactionId){
        $order->buyerPay = $fee;
        $order->status = STATUS_BUYER_PAID;
        $order->transaction_id = $transactionId;
        $saved = $order->save();

        $feeId = $order->location;
        $feeObj = new Fee();
        $feeObj->find($feeId);

        $school = new School();
        $school->find($order->schoolId);
        $oldTime = strtotime($school->validDate);
        if($oldTime< time()){
            $oldTime = time();
        }
        $school->validDate = date("Y-m-d H:i:s",$oldTime + $feeObj->days * 24*3600);
        $school->save();

    }

    public static function saveCourseLearned($order,$user){
        //增加购买
        $course = new Course();
        $course->find($order->courseId);
        $course->buyCount = $course->buyCount+1;
        $course->save();


        //记录学过的人
        $courseLearnedObj = new CourseLearned();
        $courseLearnedObj->uid = $user->uid;
        $courseLearnedObj->courseId = $order->courseId;
        $courseLearnedObj->find();
        $courseLearnedObj->avatar = $user->avatar;
        $courseLearnedObj->nick = $user->nick;
        $courseLearnedObj->save();
    }

    //打赏老师
    public static function finishTeacher($order,$fee, $transactionId){
        $order->buyerPay = $fee;
        $order->status = STATUS_BUYER_PAID;
	    $order->transaction_id = $transactionId;
        $order->save();

        $teacher = new Teacher();
        $teacher->find($order->teacherId);
        $teacher->likeCount = $teacher->likeCount+1;
        $teacher->save();        
    }


    public static function finishByResult($result){
        $orderInfo = explode('--',$result['out_trade_no']);
        
        $fee = $result['cash_fee']/100;
        //$shopId = intval($orderInfo[0]);
        $orderId = intval($orderInfo[1]);
        $order = new Order();
        $order->find(['orderId'=>$orderId]);
        if($order->orderType == ORDER_TYPE_FEE) {//续费订单
            self::finishFee($order,$fee, $result['transaction_id']);
        }else if($order->orderType == ORDER_TYPE_LIKE){
            self::finishTeacher($order,$fee, $result['transaction_id']);
        }else{//课程订单或者老师打赏
            self::finishCourse($order,$fee, $result['transaction_id']);
        } 
        
    }

}